package soar.template.springboot.service.hello.service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.persistence.EntityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import soar.template.springboot.service.hello.appconfig.rabbitmq.Config;

@Service
public class TestService extends BaseService
{
    private final static Logger logger = LoggerFactory
            .getLogger(TestService.class);

    public String run(String echo)
    {
        String response = String.format("你好！ hello: %s @ %s", echo,
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
                        .format(LocalDateTime.now()));
        logger.info("ok");
        logger.info("config.alipay.url: {}", appConfig.alipay.url);

        try
        {
            Config main = appConfig.rabbitmq.main;
            mainRabbitTemplate.convertAndSend(main.exchange, main.queue,
                    response);
        }
        catch (Exception e)
        {
            logger.error("mq fail: {}", e);
        }

        mainExecutor.execute(() -> {
            EntityManager main_em = null;

            try
            {
                main_em = mainEntityManagerFactory.createEntityManager();

                main_em.getTransaction().begin();

                main_em.getTransaction().commit();

                Thread.sleep(2 * 1000);
            }
            catch (Exception e)
            {
                if (e.getMessage() != null)
                    logger.error("fail: {}", e);
                try
                {
                    if (main_em != null && main_em.getTransaction().isActive())
                        main_em.getTransaction().rollback();
                }
                catch (Exception er)
                {
                    logger.error("rollback fail: {}", er);
                }
            }
            finally
            {
                if (main_em != null)
                    main_em.close();
            }
            logger.info("{}", response);
        });
        return response;
    }

}
